<?php
class LeeNT_GuidSystem
{
	function currentTimeMillis()
	{
		list($usec, $sec) = explode(" ", microtime());
		return $sec . substr($usec, 2, 3);
	}
}

class LeeNT_NetAddress
{
	var $Name = 'localhost';
	var $IP   = '127.0.0.1';
	
	function getLocalHost()
	{
		$address = new LeeNT_NetAddress();
		$address->Name = $_ENV["COMPUTERNAME"];
		$address->IP = $_SERVER["SERVER_ADDR"];
		return $address;
	}
	
	function toString()
	{
		return strtolower($this->Name . '/' . $this->IP);
	}
}

class LeeNT_GuidRandom
{
	function nextLong()
	{
		$tmp = rand(0, 1) ? '-' : '';
		return $tmp . rand(1000, 9999) . rand(1000, 9999) . rand(1000, 9999) . rand(100, 999) . rand(100, 999);
	}
}

class LeeNT_Guid
{
	var $valueBeforeMD5;
	var $valueAfterMD5;
	
	function __construct()
	{
		$this->getGuid();
	}
	
	function getGuid()
	{
		$address = LeeNT_NetAddress::getLocalHost();
		$this->valueBeforeMD5 = $address->toString() . ':' . LeeNT_GuidSystem::currentTimeMillis() . ':' . LeeNT_GuidRandom::nextLong();
		$this->valueAfterMD5 = md5($this->valueBeforeMD5);
	}
	
	function newGuid()
	{
		$Guid = new LeeNT_Guid();
		return $Guid;
	}
	
	/**
	 * 生成 GUID 字符串。
	 *
	 * @return string
	 */
	function toString()
	{
		$raw = strtoupper($this->valueAfterMD5);
		return substr($raw, 0, 8) . '-' . substr($raw, 8, 4) . '-' . substr($raw, 12, 4) . '-' . substr($raw, 16, 4) . '-' . substr($raw, 20);
	}
	
	/**
	 * 静态返回一个 Guid 对象。
	 *
	 * @return LeeNTGuid
	 */
	static function getInstance()
	{
		return (new LeeNT_Guid());
	}
}